How to seed data in .NET Core 6 with Entity Framework?
How to seed data in .NET Core 6 with Entity Framework?
29807-Nov-2023
Updated on 08-Nov-2023
Home / DeveloperSection / Forums / How to seed data in .NET Core 6 with Entity Framework?
How to seed data in .NET Core 6 with Entity Framework?
Aryan Kumar
08-Nov-2023In .NET Core 6 with Entity Framework, you can seed data into your database during application startup. This is commonly done to initialize the database with default or sample data. To seed data, follow these steps:
Create a Class for Seeding Data: Start by creating a class that will contain the data you want to seed. This class can be placed anywhere in your project. For example:
In this example, SeedData is a class containing a static Initialize method that seeds data into the database. Replace YourDbContext with the name of your database context, and YourEntity with the name of your entity class.
Call the SeedData Method in Program.cs: In your Program.cs file, call the SeedData.Initialize method to seed data during application startup. You can do this inside the Main method before running the application:
Run the Application: When you run your application, the SeedData.Initialize method will be called during application startup. It will check if data already exists in the database and seed the data only if it's not already present.
Make sure to replace YourDbContext with the name of your database context, and YourEntity with the name of your entity class. Also, customize the data you want to seed in the initialData list as needed.
By following these steps, you can seed data into your database when your .NET Core 6 application starts, ensuring that the database is initialized with the desired data.